package com.ocm.core.domain;

import java.util.ArrayList;
import java.util.List;

import com.ocm.core.exception.ExceptionCode;
import com.ocm.core.exception.TypeCodeException;
import com.ocm.core.exception.UnsupportTypeException;

public enum Permission {
   VIEWPROPERTIES(1), MODIFYPROPERTIES(2), DELETE(4), CREATEINSTANCE(8), VIEWPERMISSION(16), MODIFYPERMISSON(32), DOWNLOAD(64), LINK(128);

   private static final int NUMBER_PERMISSIONS = 8;

   private int permission;

   public int getPermission() {
      return this.permission;
   }

   private Permission(int permission) {
      this.permission = permission;
   }

   public static Permission getPermssion(int type) throws UnsupportTypeException {
      Permission value = null;
      switch (type) {
         case 1:
            value = Permission.VIEWPROPERTIES;
            break;
         case 2:
            value = Permission.MODIFYPROPERTIES;
            break;
         case 4:
            value = Permission.DELETE;
            break;
         case 8:
            value = Permission.CREATEINSTANCE;
            break;
         case 16:
            value = Permission.VIEWPERMISSION;
            break;
         case 32:
            value = Permission.MODIFYPERMISSON;
            break;
         case 64:
            value = Permission.DOWNLOAD;
            break;
         case 128:
            value = Permission.LINK;
            break;
         default:
            throw new UnsupportTypeException(ExceptionCode.instance(TypeCodeException.class,
                  TypeCodeException.PERMISSIONTYPE));
      }
      return value;
   }
   
   public static Permission[] getPermissions(int access) throws UnsupportTypeException {
      List<Permission> pers = new ArrayList<Permission>();
      for (int bit = 0; bit < NUMBER_PERMISSIONS; ++bit)
      {
        int mask = 1 << bit;
        if ((access & mask) == 0)
          continue;
        pers.add(pers.size(), getPermssion(mask));
      }
      Permission[] permissions = pers.toArray(new Permission[]{});
      return permissions;
   }

   public static int getAccessMask(Permission... permissions) throws UnsupportTypeException {
      int accessMask = 0;
      for (Permission permission : permissions){
         accessMask += permission.getPermission();
      }
      return accessMask;
   }
}
